﻿#pragma execution-character_set("UTF-8")
#include "LusterDBTool.h"
#include <QFileDialog>
#include <QHeaderView>
#include <QMessageBox>
#include <QLabel>
#include <QSvgWidget>
#include <QFileInfo>
#include <QDebug>

LusterDBTool::LusterDBTool(QWidget *parent)
    : QMainWindow(parent)
{
	ui.setupUi(this);
	setWindowTitle(QStringLiteral("资源管理器"));
	InitUI();
	InitSlots();
}

LusterDBTool::~LusterDBTool()
{}

void LusterDBTool::SlotSelectDbFile()
{
	QString selectFilePath = QFileDialog::getOpenFileName(this, QStringLiteral("选择资源数据库"), "../../", "*.db");
	if (selectFilePath.isEmpty())
		return;
	ui.db_path_lineEdit->setText(selectFilePath);
}

void LusterDBTool::SlotConnectResDb()
{
	if (ui.db_path_lineEdit->text().isEmpty())
		return;
	bool connectDB = control_db_Ptr_->ConnectNewDatabase(ui.db_path_lineEdit->text());
	if (!connectDB)
	{
		QMessageBox::critical(this, QStringLiteral("错误"), "数据库连接失败！");
		statusBar()->showMessage(QStringLiteral("错误:数据库连接失败!"));
		return;
	}
	else
		statusBar()->showMessage(QStringLiteral("提示:数据库连接成功!"));
	int curType = ui.type_comboBox->currentIndex();
	if (curType == 0)
		RefreshPngTable();
	else if (curType == 1)
		RefreshSvgTable();
	else
	{ }
	SetControlDbBtnEnable(true);
}

void LusterDBTool::SlotImportResource()
{
	if (ui.type_comboBox->currentIndex() == 0)
	{
		ImportPng();
		RefreshPngTable();
	}
	else if (ui.type_comboBox->currentIndex() == 1)
	{
		ImportSvg();
		RefreshSvgTable();
	}
	else
	{
	}
}

void LusterDBTool::SlotResourceNameChanged(QTableWidgetItem* _curItem)
{
	if (!_curItem)
		return;
	int changedRow = _curItem->row();
	if (!ui.db_data_tableWidget->item(changedRow, 0))
		return;
	if (!ui.db_data_tableWidget->item(changedRow, 2))
		return;
	int changedId = ui.db_data_tableWidget->item(changedRow, 0)->text().toInt();
	QString changedName = ui.db_data_tableWidget->item(changedRow, 2)->text();
	// 更新数据库数据
	if (ui.type_comboBox->currentIndex() == 0)
	{
		// 更新图片数据
		control_db_Ptr_->UpdatePicData(changedId, changedName);
	}
	else if (ui.type_comboBox->currentIndex() == 1)
	{
		// 更新SVG数据
		control_db_Ptr_->UpdateSvgData(changedId, changedName);
	}
	else
	{

	}
	qDebug() << changedId << changedName;
	QString changeText = QStringLiteral("更新资源ID:") + QString::number(changedId) + QStringLiteral("名称为") + changedName;
	statusBar()->showMessage(changeText);
}

void LusterDBTool::SlotUpdateSelectResource()
{
	// 只能选中一个更新
	QVector<int> selectRowList = GetTableSelectRows();
	if (selectRowList.size() != 1)
	{
		QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("只能选择一行进行资源更新"));
		return;
	}
	int selectId = ui.db_data_tableWidget->item(selectRowList.first(), 0)->text().toInt();
	QString selectName = ui.db_data_tableWidget->item(selectRowList.first(), 2)->text();
	// 选择一个新的资源
	QString fileSuffix = ui.type_comboBox->currentIndex() == 0 ? "Images(*.jpg *.png *.JPG *.PNG)" : "*.svg";
	QString selectFilePath = QFileDialog::getOpenFileName(this, "选择资源文件", "../../", fileSuffix);
	if (selectFilePath.isEmpty())
		return;
	QFile picFile(selectFilePath);
	picFile.open(QIODevice::ReadOnly);
	QByteArray readBuf = picFile.readAll();
	QFileInfo picFileInfo(selectFilePath);
	if (ui.type_comboBox->currentIndex() == 0)
	{
		control_db_Ptr_->UpdatePicData(selectId, picFileInfo.baseName(), readBuf);
		RefreshPngTable();
	}
	else
	{
		control_db_Ptr_->UpdateSvgData(selectId, picFileInfo.baseName(), readBuf);
		RefreshSvgTable();
	}
	picFile.close();
}

void LusterDBTool::SlotDeleteSelectRes()
{
	QVector<int> selectRowList = GetTableSelectRows();
	if (selectRowList.size() <= 0)
		return;
	for (const auto& curRow:selectRowList)
	{
		int curId = ui.db_data_tableWidget->item(curRow, 0)->text().toInt();
		if (ui.type_comboBox->currentIndex() == 0)
			control_db_Ptr_->DeletePicById(curId);
		else if (ui.type_comboBox->currentIndex() == 1)
			control_db_Ptr_->DeleteSvgById(curId);
	}
	ui.type_comboBox->currentIndex() == 0 ? RefreshPngTable() : RefreshSvgTable();
}

void LusterDBTool::SlotExportSelectRes()
{
	QVector<int> selectRowList = GetTableSelectRows();
	if (selectRowList.size() == 0)
		return;

	QString savePath = QFileDialog::getExistingDirectory(this, "保存文件夹", "../../");
	if (savePath.isEmpty())
		return;

	for (const auto& curRow : selectRowList)
	{
		int curId = ui.db_data_tableWidget->item(curRow, 0)->text().toInt();

		if (ui.type_comboBox->currentIndex() == 0)
		{
			ResourceDataSPtr picBuffer = control_db_Ptr_->QueryPicById(curId);
			QFile saveFile(savePath + "/" + picBuffer->name + ".png");
			saveFile.open(QIODevice::WriteOnly);
			saveFile.write(QByteArray::fromBase64(picBuffer->pbgBuffer));
			saveFile.close();
		}
		else if (ui.type_comboBox->currentIndex() == 1)
		{
			ResourceDataSPtr svgContent = control_db_Ptr_->QuerySvgById(curId);
			QFile saveFile(savePath + "/" + svgContent->name + ".svg");
			saveFile.open(QIODevice::WriteOnly);
			saveFile.write(svgContent->svgContent.toUtf8());
			saveFile.close();
		}
	}
}

void LusterDBTool::SlotSearchResource(const QString& _curSearchName)
{
	ResourceDataList queryRes;
	if (ui.type_comboBox->currentIndex() == 0)
	{
		queryRes = control_db_Ptr_->QueryPictureByName(_curSearchName);
		ui.db_data_tableWidget->clearContents();
		ui.db_data_tableWidget->setRowCount(0);
		ui.db_data_tableWidget->setRowCount(queryRes.size());

		for (int i = 0; i < queryRes.size(); ++i)
		{
			const auto& curSvgData = queryRes.at(i);
			ui.db_data_tableWidget->setItem(i, 0, CreateTableItem(QString::number(curSvgData->id), true));
			QLabel* bgWidget = new QLabel();
			QPixmap bgPix;
			bgPix.loadFromData(curSvgData->pbgBuffer);
			bgPix = bgPix.scaled(50, 50, Qt::KeepAspectRatio);
			bgWidget->setPixmap(bgPix);

			ui.db_data_tableWidget->setCellWidget(i, 1, bgWidget);
			ui.db_data_tableWidget->setItem(i, 2, CreateTableItem(curSvgData->name, false));
			ui.db_data_tableWidget->setItem(i, 3, CreateTableItem(curSvgData->picType == ControlDB::JPG ? "JPG" : "PNG", true));
			ui.db_data_tableWidget->setRowHeight(i, 50);
		}
	}
	else if (ui.type_comboBox->currentIndex() == 1)
	{
		queryRes = control_db_Ptr_->QuerySvgByName(_curSearchName);
		ui.db_data_tableWidget->clearContents();
		ui.db_data_tableWidget->setRowCount(0);
		ui.db_data_tableWidget->setRowCount(queryRes.size());
		for (int i = 0; i < queryRes.size(); ++i)
		{
			const auto& curSvgData = queryRes.at(i);
			ui.db_data_tableWidget->setItem(i, 0, CreateTableItem(QString::number(curSvgData->id), true));
			QSvgWidget* bgWidget = new QSvgWidget();
			bgWidget->load(curSvgData->svgContent.toUtf8());
			ui.db_data_tableWidget->setCellWidget(i, 1, bgWidget);
			ui.db_data_tableWidget->setItem(i, 2, CreateTableItem(curSvgData->name, false));
			ui.db_data_tableWidget->setItem(i, 3, CreateTableItem("SVG", true));
		}
	}
}

void LusterDBTool::InitUI()
{
	control_db_Ptr_ = std::make_shared<ControlDB>();
	SetControlDbBtnEnable(false);
	ui.db_path_lineEdit->setReadOnly(true);
	ui.search_lineEdit->setPlaceholderText(QStringLiteral("请输入查询资源名字"));
	ui.db_data_tableWidget->verticalHeader()->setHidden(false);
	ui.db_data_tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
	ui.db_data_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
	QStringList resTableHeaderLabels;
	resTableHeaderLabels << "ID" << QStringLiteral("示例") << QStringLiteral("唯一名称") << QStringLiteral("类型");
	ui.db_data_tableWidget->setColumnCount(resTableHeaderLabels.size());
	ui.db_data_tableWidget->setHorizontalHeaderLabels(resTableHeaderLabels);
}

void LusterDBTool::InitSlots()
{
	connect(ui.chose_dbpath_pushButton, &QPushButton::clicked, this, &LusterDBTool::SlotSelectDbFile);
	connect(ui.connect_db_pushButton, &QPushButton::clicked, this, &LusterDBTool::SlotConnectResDb);
	connect(ui.type_comboBox, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int _curIndex) {
		if (_curIndex == 0)
			RefreshPngTable();
		else if (_curIndex == 1)
			RefreshSvgTable();
		else
		{ }
	});
	connect(ui.import_pushButton, &QPushButton::clicked, this, &LusterDBTool::SlotImportResource);
	connect(ui.db_data_tableWidget, &QTableWidget::itemChanged, this, &LusterDBTool::SlotResourceNameChanged);
	connect(ui.update_select_pushButton, &QPushButton::clicked, this, &LusterDBTool::SlotUpdateSelectResource);
	connect(ui.delete_select_pushButton, &QPushButton::clicked, this, &LusterDBTool::SlotDeleteSelectRes);
	connect(ui.export_select_pushButton, &QPushButton::clicked, this, &LusterDBTool::SlotExportSelectRes);
	connect(ui.search_lineEdit, &QLineEdit::textChanged, this, &LusterDBTool::SlotSearchResource);
}

void LusterDBTool::RefreshPngTable()
{
	ui.db_data_tableWidget->blockSignals(true);  //屏蔽掉信号，这样就不会触发itemChanged信号
	ui.db_data_tableWidget->clearContents();
	ui.db_data_tableWidget->setRowCount(0);
	ResourceDataList dataList = control_db_Ptr_->QueryPictureDataList();
	ui.db_data_tableWidget->setRowCount(dataList.size());
	for (int i=0;i<dataList.size();++i)
	{
		const auto& curPngData = dataList.at(i);
		ui.db_data_tableWidget->setItem(i, 0, CreateTableItem(QString::number(curPngData->id), true));
		QLabel* bgWidget = new QLabel();
		QPixmap pngPix;
		pngPix.loadFromData(curPngData->pbgBuffer);
		pngPix = pngPix.scaled(50, 50, Qt::KeepAspectRatio);
		bgWidget->setPixmap(pngPix);
		ui.db_data_tableWidget->setCellWidget(i, 1, bgWidget);
		ui.db_data_tableWidget->setItem(i, 2, CreateTableItem(curPngData->name, false));
		ui.db_data_tableWidget->setItem(i, 3, CreateTableItem(curPngData->picType == ControlDB::JPG ? "JPG" : "PNG", true));
		ui.db_data_tableWidget->setRowHeight(i, 50);
	}
	ui.db_data_tableWidget->blockSignals(false);
}

void LusterDBTool::RefreshSvgTable()
{
	ui.db_data_tableWidget->blockSignals(true);
	ui.db_data_tableWidget->clearContents();
	ui.db_data_tableWidget->setRowCount(0);
	ResourceDataList dataList = control_db_Ptr_->QuerySvgDataList();
	ui.db_data_tableWidget->setRowCount(dataList.size());
	for (int i=0;i<dataList.size();++i)
	{
		const auto curSvgData = dataList.at(i);
		ui.db_data_tableWidget->setItem(i, 0, CreateTableItem(QString::number(curSvgData->id), true));
		QSvgWidget* svgWidget = new QSvgWidget();
		svgWidget->setFixedSize(50, 50);
		svgWidget->load(curSvgData->svgContent.toUtf8());
		ui.db_data_tableWidget->setCellWidget(i, 1, svgWidget);
		ui.db_data_tableWidget->setItem(i, 2, CreateTableItem(curSvgData->name, false));
		ui.db_data_tableWidget->setItem(i, 3, CreateTableItem("SVG", true));
		ui.db_data_tableWidget->setRowHeight(i, 50);
	}
	ui.db_data_tableWidget->blockSignals(false);
}

QTableWidgetItem* LusterDBTool::CreateTableItem(const QString& _text, const bool& _isReadOnly)
{
	QTableWidgetItem* curItem = new QTableWidgetItem();
	curItem->setText(_text);
	curItem->setTextAlignment(Qt::AlignCenter);
	if (_isReadOnly)
		curItem->setFlags(Qt::ItemIsEnabled);
	return curItem;
}

void LusterDBTool::SetControlDbBtnEnable(bool _is_enable)
{
	ui.export_select_pushButton->setEnabled(_is_enable);
	ui.update_select_pushButton->setEnabled(_is_enable);
	ui.import_pushButton->setEnabled(_is_enable);
	ui.delete_select_pushButton->setEnabled(_is_enable);
}

void LusterDBTool::ImportPng()
{
	QStringList importFileList = QFileDialog::getOpenFileNames(this, "导入图片资源", "../../", "Images(*.jpg *.png *.JPG *.PNG)");
	if (importFileList.size() == 0)
		return;
	for (const auto& picFilePath:importFileList)
	{
		QFile picFile(picFilePath);
		picFile.open(QIODevice::ReadOnly);
		QByteArray readBuf = picFile.readAll();
		QFileInfo picFileInfo(picFilePath);
		ControlDB::PictureType picType = picFileInfo.suffix().compare("png") == 0 ? ControlDB::PNG : ControlDB::JPG;
		control_db_Ptr_->ImportPicture(picFileInfo.baseName(), readBuf, picType);
		picFile.close();
	}
	statusBar()->showMessage(QStringLiteral("导入图像成功"));
}

void LusterDBTool::ImportSvg()
{
	QStringList importFileList = QFileDialog::getOpenFileNames(this, "导入SVG资源", "../../", "Images(*.svg)");
	if (importFileList.size() == 0)
		return;
	for (const auto& picFilePath:importFileList)
	{
		QFile picFile(picFilePath);
		picFile.open(QIODevice::ReadOnly);
		QByteArray readBuf = picFile.readAll();
		QFileInfo picFileInfo(picFilePath);
		control_db_Ptr_->ImportSvg(picFileInfo.baseName(), readBuf);
		picFile.close();
	}
}

QVector<int> LusterDBTool::GetTableSelectRows()
{
	QVector<int> selectRowList;
	QList<QTableWidgetItem*> selectItemList = ui.db_data_tableWidget->selectedItems();
	for (const auto& selectItem : selectItemList)
	{
		int curRow = selectItem->row();
		if(selectRowList.contains(curRow))
			continue;
		selectRowList.push_back(curRow);
	}
	return selectRowList;
}
